#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>

#include "stack.h"


int check(Stack *data, char simb)
{
	

	switch (simb)
	{
	case  '+':	  stack_push(data, (Pointer)((int)stack_pop(data) + (int)stack_pop(data)));	return 3;
	case  '-':	  stack_push(data, (Pointer)(-(int)stack_pop(data) + (int)stack_pop(data)));return 3;
	case  '*':    stack_push(data, (Pointer)((int)stack_pop(data) * (int)stack_pop(data)));	return 3;
	case  '/':  if (stack_peek(data) != 0)
				 {   stack_push(data, (Pointer)(1 / (int)stack_pop(data) * (int)stack_pop(data)));
					 return 3;
				 }
				else {printf("ERROR, division by zero/n");
				return 3;}
				
	case '\0':    printf("\n__ %d\n", stack_peek(data)); return 2;		 
	case  'e':    return 0;	
	default:	  printf("error enter\n"); return 0;
	}

	return 1;
}

int enter(Stack* data)
{
	int i = 0;
	long a;
	int beg, end1;

	char *buffer = (char*) malloc(100 * sizeof(char));
	char *start = buffer;
	char *stop = buffer;
	
	printf("\n > ");
	gets(buffer);		
	
	while(1){
		a = strtol(start, &stop, 10);

		if(stop == start){
			while(isspace((int)*start)){
				start++;
			}
			beg = check(data, *start); 
			start++;

			if (beg == 0){
				free(buffer);
				return 1;
			}

			if(beg == 2)
			{
				end1 = enter(data);
				return end1;
			}

		}
		else{
			start = stop;
			stack_push(data, (Pointer)a);
		}
	}

	free(buffer);
}

void main()
{
	Stack data;
			
	stack_tune(&data, 1, 1);
	stack_create(&data);
	
	enter(&data);
	
	stack_destroy(&data);
	system("pause");
}